<template>
	<view class="buy-course-container">
		<uv-toast ref="toast"></uv-toast>
		<PLoader :loading="loading" backgroundColor="#00000065"></PLoader>

		<!-- 课程信息卡片 -->
		<view class="course-card">
			<image class="course-image" :src="courseDetail.image" mode="aspectFill"></image>
			<view class="course-info">
				<text class="course-title">{{ courseDetail.name }}</text>
				<view class="course-stats">
					<text class="duration">总时长：{{ totalDuration }}</text>
					<text class="lesson-count">{{ medias.length }}课时</text>
				</view>
			</view>
		</view>

		<!-- 价格信息 -->
		<view class="price-section">
			<view class="price-row">
				<text>课程原价</text>
				<text class="original-price">¥{{ courseDetail.originalPrice || 0 }}</text>
			</view>
			<view class="price-row">
				<text>优惠价格</text>
				<text class="current-price">¥{{ courseDetail.price || 0 }}</text>
			</view>
		</view>

		<!-- 购买须知 -->
		<view class="notice-section">
			<view class="section-title">购买须知</view>
			<view class="notice-item">
				<text class="dot">•</text>
				<text>购买后可永久观看</text>
			</view>
			<view class="notice-item">
				<text class="dot">•</text>
				<text>支持多端观看学习</text>
			</view>
		</view>

		<!-- 底部购买按钮 -->
		<view class="bottom-bar">
			<view class="price-display">
				<text class="symbol">¥</text>
				<text class="amount">{{ courseDetail.price || 0 }}</text>
			</view>
			<button class="buy-btn" @tap="handleBuy">支付</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				mediasPagenation: {
					total: 0,
					current: 1,
					pageSize: 100,
				},
				loading: false,
				medias: [],
				courseDetail: {},
				courseId: 0,
				totalDuration: '00:00:00',
			}
		},

		methods: {
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			// 调起微信支付
			async handleBuy() {
				try {
					this.loading = true;
					// 1. 获取支付参数 创建订单
					const payRes = await this.$http.post(`/course/pre/order?courseId=${this.courseId}`);

					if (!payRes) {
						throw new Error('获取支付参数失败');
					}

					// 3. 调起微信支付
					wx.requestPayment({
						nonceStr: payRes.nonceStr,
						paySign: payRes.paySign,
						signType: payRes.signType,
						timeStamp: payRes.timeStamp,
						package: payRes.package,
						success: () => {
							this.showToast('支付成功', 'success');
							// 支付成功后跳转结果页
							uni.redirectTo({
								url: `/subpkg/pay_result/pay_result?orderNo=${payRes.orderNo}`
							});
						},
						fail: (err) => {
							// 发起请求删除订单信息
							this.$http.post(`/order/del?orderNo=${payRes.orderNo}`);
						}
					});
				} catch (e) {
					console.error('购买失败:', e);
					this.showToast(e.msg || '购买失败');
				} finally {
					this.loading = false;
				}
			},
			async initData() {
				this.loading = true;
				try {
					await Promise.all([
						this.fetchCourseDetail(),
						this.fetchCourseMedia()
					]);
				} catch (e) {
					console.error('初始化数据失败:', e);
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				} finally {
					this.loading = false;
				}
			},
			async fetchBatchVideoInfos() {
				try {
					this.loading = true;
					const videoIds = this.medias.map(item => item.videoId).join(',');

					// 如果没有videoIds则直接返回
					if (!videoIds) return;

					const data = await this.$http.post(`/courses/media/batch/video/infos?videoIds=${videoIds}`);

					if (data && Array.isArray(data)) {
						// 将点播信息数据转换为以videoId为key的映射对象，方便查找
						const videoInfoMap = data.reduce((map, item) => {
							map[item.videoId] = item;
							return map;
						}, {});

						// 更新medias数组，添加coverUrl和duration字段
						this.medias = this.medias.map(media => {
							const videoInfo = videoInfoMap[media.videoId] || {};

							return {
								...media,
								coverImageUrl: media.coverImageUrl || videoInfo.coverURL, // 如果没有新的封面则使用原封面
								duration: videoInfo.duration || 0
							};
						});
					}
					this.calculateTotalDuration();
				} catch (e) {
					console.error(e);
					this.showToast(e.msg || '获取点播信息失败');
				} finally {
					this.loading = false;
				}
			},
			// 格式化视频时长
			formatDuration(seconds) {
				if (!seconds) return '00:00';
				// 将字符串转为数字
				seconds = Number(seconds);
				const h = Math.floor(seconds / 3600);
				const m = Math.floor((seconds % 3600) / 60);
				const s = Math.floor(seconds % 60);

				if (h > 0) {
					return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
				}
				return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
			},
			// 计算总时长
			calculateTotalDuration() {
				const totalSeconds = this.medias.reduce((total, media) => {
					return total + (Number(media.duration) || 0);
				}, 0);
				this.totalDuration = this.formatDuration(totalSeconds);
			},
			async fetchCourseMedia() {
				try {
					this.loading = true;
					const obj = {
						...this.mediasPagenation,
						courseId: this.courseId
					};
					const data = await this.$http.post('/courses/media/list', obj);

					if (data) {
						this.mediasPagenation.total = data.count;
						this.mediasPagenation.current += 1;
						this.medias = data.items;
					}

					await this.fetchBatchVideoInfos();
				} catch (e) {
					console.error(e);
					this.showToast(e.msg || '获取课程详情失败');
				} finally {
					this.loading = false;
				}
			},
			async fetchCourseDetail() {
				try {
					this.loading = true;

					const res = await this.$http.get(`/course/info?courseId=${this.courseId}`);

					if (res) {
						this.courseDetail = {
							...this.courseDetail,
							...res
						};
					} else {
						throw new Error(res.msg || '获取课程详情失败');
					}
				} catch (e) {
					console.error('获取课程详情失败:', e);
					this.showToast(e.msg || '获取课程详情失败');
				} finally {
					this.loading = false;
				}
			},
		},

		async onLoad(options) {
			if (options.courseId) {
				this.courseId = options.courseId;
				await this.initData();
			} else {
				this.showToast('暂无课程信息');
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import 'buy_course.scss';
</style>